package com.jf3q.front.service.es;

import com.alibaba.fastjson.JSON;
import com.jf3q.common.es.entity.CourseEntity;
import com.jf3q.common.es.repository.CourseEntityRepository;
import com.jf3q.front.dto.SearchCourseDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchPage;
import org.springframework.stereotype.Service;

import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CourseEntityService {
    @Autowired
    private CourseEntityRepository courseEntityRepository;

    //为了高亮显示重新封装了page
    public Page<CourseEntity> searchByKeyword(String keyword, Integer number, Integer size) {
        if (!StringUtils.hasText(keyword.trim())) {
            throw new RuntimeException("必须输入关键词");
        }
        //先把高亮显示的处理掉 执行搜索并获取高亮显示的搜索结果
        List<SearchHit<CourseEntity>> searchHits = courseEntityRepository.searchByHit(keyword);
        List<CourseEntity> newCourseList = new ArrayList<>();
        for (SearchHit<CourseEntity> searchHit : searchHits) {
            //表示搜索结果中的实际数据内容
            CourseEntity content = searchHit.getContent();
            //获取高亮字段的映射信息
            Map<String, List<String>> highlightMap = searchHit.getHighlightFields();
            if (highlightMap != null) {
                for (Map.Entry<String, List<String>> entry : highlightMap.entrySet()) {
                    //获取字段名和高亮内容
                    String originalField = entry.getKey();
                    List<String> highlightContent = entry.getValue();
                    if (highlightContent != null && !highlightContent.isEmpty()) {
                        //根据字段名设置高亮内容
                        if (originalField.equals("title")) {
                            content.setTitle(highlightContent.get(0));
                        } else if (originalField.equals("description")) {
                            content.setDescription(highlightContent.get(0));
                        } else if (originalField.equals("subjectName")) {
                            content.setSubjectName(highlightContent.get(0));
                        } else if (originalField.equals("subjectParentName")) {
                            content.setSubjectParentName(highlightContent.get(0));
                        }
                    }
                }
            }
            newCourseList.add(content);
        }
        Pageable pageable = PageRequest.of(number-1, size);
        // 计算总记录数
        int totalElements = searchHits.size();

        // 创建一个新的PageImpl对象
        Page<CourseEntity> page = new PageImpl<>(
                // 将SearchHit中的CourseEntity对象提取出来，并放入一个新的列表中
                newCourseList.stream()
                        .skip(pageable.getPageNumber() * pageable.getPageSize()) // 跳过当前页之前的所有记录
                        .limit(pageable.getPageSize()) // 限制结果集大小
                        .collect(Collectors.toList()),// 将处理后的流收集为一个 List
                pageable, // 分页参数
                totalElements // 总记录数
        );
        // 返回新的Page对象
        return page;
    }

    public Page<CourseEntity> searchBySubject(SearchCourseDto dto, Integer number, Integer size) {

        //传了二级分类
        if (StringUtils.hasText(dto.getSubjectId().trim())) {

            //传了排序
            if (StringUtils.hasText(dto.getSortField().trim())) {
                if (dto.getSortType().equals("des")) {
                    return courseEntityRepository.findBySubjectId(dto.getSubjectId(), PageRequest.of(number - 1, size, Sort.by(dto.getSortField()).descending()));
                } else {
                    return courseEntityRepository.findBySubjectId(dto.getSubjectId(), PageRequest.of(number - 1, size, Sort.by(dto.getSortField()).ascending()));
                }
            } else {
                //没传排序
                return courseEntityRepository.findBySubjectId(dto.getSubjectId(), PageRequest.of(number - 1, size));
            }
        }
        //传了一级分类
        if (StringUtils.hasText(dto.getSubjectParentId().trim())) {

            //传了排序
            if (StringUtils.hasText(dto.getSortField().trim())) {
                if (dto.getSortType().equals("des")) {
                    return courseEntityRepository.findBySubjectParentId(dto.getSubjectParentId(), PageRequest.of(number - 1, size, Sort.by(dto.getSortField()).descending()));
                } else {
                    return courseEntityRepository.findBySubjectParentId(dto.getSubjectParentId(), PageRequest.of(number - 1, size, Sort.by(dto.getSortField()).ascending()));
                }
            } else {
                //没传排序
                return courseEntityRepository.findBySubjectParentId(dto.getSubjectParentId(), PageRequest.of(number - 1, size));
            }
        }

        //只传排序
        if (StringUtils.hasText(dto.getSortField().trim())) {
            if (dto.getSortType().equals("des")) {
                return courseEntityRepository.findAll(PageRequest.of(number - 1, size, Sort.by(dto.getSortField()).descending()));
            } else {
                return courseEntityRepository.findAll(PageRequest.of(number - 1, size, Sort.by(dto.getSortField()).ascending()));
            }
        }
        //什么都不传的情况下查所有
        return courseEntityRepository.findAll(PageRequest.of(number - 1, size));
    }
    }
